package club.fuwenhao.netty;

import club.fuwenhao.bean.BaseMsg;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author fwh
 * @Description 客户端处理类
 * @email fuwenhao594@163.com
 * @date 2021/10/27 10:24 下午
 */
@Slf4j
public abstract class BaseNettyClientHandler extends SimpleChannelInboundHandler<BaseMsg> {
    /**
     * 接收服务端消息
     *
     * @param ctx
     * @param msg
     * @return void
     * @author fwh [2021/10/27 && 10:25 下午]
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("服务端地址为:{}", ctx.channel().remoteAddress());
        log.info("接收服务端消息为:{}", msg.toString());
    }

    /**
     * 客户端链接到服务器触发此方法
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        final String msg = "客户端地址：" + ctx.channel().localAddress() + "已上线";
        final ByteBuf byteBuf = Unpooled.copiedBuffer(msg.getBytes(CharsetUtil.UTF_8));
        ctx.writeAndFlush(byteBuf);
    }

}
